/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.snda.dw.lidejia.hadooptotalsort.type;

import com.snda.dw.lidejia.hadooptotalsort.meta.SortKeyMetaPool;
import com.snda.dw.lidejia.hadooptotalsort.meta.SortKeyMeta;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.hadoop.io.WritableComparable;
import org.apache.hadoop.io.WritableComparator;

/**
 *
 * @author lidejia
 */
public class SortKeys implements WritableComparable<SortKeys> {
    
    static {
        WritableComparator.define(SortKeys.class, new SortKeysComparator());
    }

    private List<WritableComparable> keys = new ArrayList<WritableComparable>();
    private List<SortKeyMeta> metas;

    public SortKeys() {
        super();
        //
        this.metas = SortKeyMetaPool.getInstance().getMetas();
    }

    public void addKey(WritableComparable key) {
        this.keys.add(key);
    }

    public void setKeys(List<WritableComparable> keys) {
        this.keys.clear();
        this.keys.addAll(keys);
    }

    @Override
    public void write(DataOutput d) throws IOException {
        for (WritableComparable key : keys) {
            key.write(d);
        }
    }

    @Override
    public void readFields(DataInput di) throws IOException {
        for (SortKeyMeta meta : metas) {
            WritableComparable instance = meta.createInstance();
            instance.readFields(di);
            keys.add(instance);
        }
    }

    @Override
    public int compareTo(SortKeys t) {
        int cmp = 0;
        for (int i = 0; i < metas.size(); i++) {
            WritableComparable self = keys.get(i);
            WritableComparable that = t.keys.get(i);
            cmp = metas.get(i).compare(self, that);
            if (cmp != 0) {
                break;
            }
        }
        return cmp;
    }
}
